package cn.zhqr.core.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import org.apache.log4j.Logger;


/**
 * 跨域处理
 * Created by charles on 2018/6/20.
 */
public class CorsInterceptor implements Interceptor{
    private static Logger log = Logger.getLogger(CorsInterceptor.class);

    private boolean writeHeader = true;
    private boolean ignoreOptions = true;
    private int accessControlMaxAge = 3600;
    private String accessControlAllowOrigin = "*";

    @Override
    public void intercept(Invocation inv) {
        Controller c = inv.getController();
        if(isWriteHeader()){
            c.getResponse().addHeader("Access-Control-Allow-Origin","*");

            c.getResponse().addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");//允许跨域的方法

            c.getResponse().addHeader("Access-Control-Allow-Headers","access-token, mobile, power-by, token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified,X-Token");//表示允许的额外header
            c.getResponse().addHeader("Access-Control-Max-Age", "3600");
            c.getResponse().addHeader("Access-Control-Allow-Credentials", "true");//必须为true
        }


        //多文件上传 getfiles必须放在最前面 否则无法取到参数

        if (StrKit.notBlank(c.getResponse().getContentType()) && c.getResponse().getContentType().contains("multipart/form-data")) {
            //resp.getFiles();
            c.getFile();
            c.getFiles();
        }
        if(isIgnoreOptions() && "options".equalsIgnoreCase(inv.getController().getRequest().getMethod())){
            inv.getController().renderNull();
            return;
        }
        inv.invoke();
    }


    public boolean isWriteHeader() {
        return writeHeader;
    }

    public CorsInterceptor setWriteHeader(boolean writeHeader) {
        this.writeHeader = writeHeader;
        return this;
    }

    public boolean isIgnoreOptions() {
        return ignoreOptions;
    }

    public CorsInterceptor setIgnoreOptions(boolean ignoreOptions) {
        this.ignoreOptions = ignoreOptions;
        return this;
    }

    public int getAccessControlMaxAge() {
        return accessControlMaxAge;
    }

    public CorsInterceptor setAccessControlMaxAge(int accessControlMaxAge) {
        this.accessControlMaxAge = accessControlMaxAge;
        return this;
    }

    public String getAccessControlAllowOrigin() {
        return accessControlAllowOrigin;
    }

    public CorsInterceptor setAccessControlAllowOrigin(String accessControlAllowOrigin) {
        this.accessControlAllowOrigin = accessControlAllowOrigin;
        return this;
    }
}
